package com.five.calendar.utils;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

/**
 * 时间
 */
public class TimeUtils {

    public static final int SECOND = 1000;

    public static final int MINUTE = 60 * SECOND;

    public static final int HOUR = 60 * MINUTE;

    public static final int DAY = 24 * HOUR;

    private static final int DEFAULT_PORT = 37;
    private static final String DEFAULT_HOST = "time-nw.nist.gov";

    public static String[] sMonth = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

    /**
     * 获取美国时间
     * @return
     */
    public static Date getUsTimer() {
        Calendar calendar = Calendar.getInstance(Locale.US);
        return calendar.getTime();
    }

    public static Date getTimer() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTime();
    }

    /**
     * 获取当前时间戳（从服务器中获取会卡UI线程）
     * @return
     */
    public static long getServiceCurrentTimer() {
        InputStream raw = null;
        try {
            long differenceBetweenEpochs = 2208988800L;
            Socket theSocket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
            raw = theSocket.getInputStream();
            long secondsSince1900 = 0;
            for (int i = 0; i < 4; i++) {
                secondsSince1900 = (secondsSince1900 << 8) | raw.read();
            }
            long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
            return secondsSince1970 > 0 ? secondsSince1970 * 1000 : System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raw != null) {
                try {
                    raw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return System.currentTimeMillis();
    }

    public static String timeFormatString(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours   = totalSeconds / 3600;
        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
        formatBuilder.setLength(0);
        if (hours > 0) {
            return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return formatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    //把时间格式化成7:00 AM
    public static String timeFormatString(long timeMs) {
        SimpleDateFormat dateformat = new SimpleDateFormat("HH:mm");
        String dateStr = dateformat.format(timeMs);
        String hours = dateStr.substring(0,2);
        int hour = Integer.valueOf(hours);
        if(hour > 12){
            dateStr = dateStr + " PM";
        }else{
            dateStr = dateStr + " AM";
        }
        return dateStr;
    }

    //格式时间成 30 Aug 2017 5:00 PM
    public static String timeFormatString(Date date) {
        String day = date.getDate() + "";
        String month = sMonth[date.getMonth()];
        String year = date.getYear() + 1900 + "";
        String hour = (date.getHours() > 12 ? (date.getHours() - 12) : date.getHours()) + "";
        if(hour.length() == 1){
            hour = "0" + hour;
        }
        String minute = date.getMinutes() + "";
        if(minute.length() == 1){
            minute = "0" + minute;
        }
        String amOrpm = (date.getHours() > 12 ? "PM" : "AM");
        String formatDate = day + " " + month + " " + year + " " + hour + ":" + minute + " " + amOrpm;
        return formatDate;
    }

    public static String timeFormatMonthDay(long timeMs){
        SimpleDateFormat dateformat = new SimpleDateFormat("MM-dd");
        String dateStr = dateformat.format(timeMs);
        return dateStr;
    }

    public static String timeFormatStringForTargetDay(Date date) {
        String day = date.getDate() + "";
        String month = sMonth[date.getMonth()];
        String year = date.getYear() + 1900 + "";
        return year + "-" + month + "-" + day;
    }

    //当前时间和设立时间之差
    public static String timeFromCreateTime(long timeMs){
        long now = System.currentTimeMillis();
        long space = timeMs - now;
        if (space < 0){
            return "00:00:00";
        }
        int day = 0;
        if (space > TimeUtils.DAY) {
            day = (int) (space / TimeUtils.DAY);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
        String time = dateFormat.format(space);
        if (day == 0) {
            return time;
        } else {
            return day + " Days " + time;
        }
    }

    public static String timeFormatToCalendarDateString(long timeMs){
        Date date = new Date(timeMs);
        String year = date.getYear() + 1900 + "";
        String month = (date.getMonth() + 1) + "";
        String day = date.getDate() + "";
        return year + "-" + month + "-" + day;
    }

    public static int getDayByTime(long start, long end){
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String startTime = sdf1.format(start);
        startTime = startTime + " 00:00:00";
        String endTime = sdf1.format(end);
        endTime = endTime + " 23:59:59";
        try {
            Date startDate = sdf2.parse(startTime);
            Date endDate = sdf2.parse(endTime);
            int count  = (int)(endDate.getTime() - startDate.getTime()) / TimeUtils.DAY + 1;
            return count;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
